package com.gosling.gosling;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.JdkUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Test20240902 {

    private final static ThreadPoolTaskExecutor executor;

    static {
        executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(10);
        //配置最大线程数
        executor.setMaxPoolSize(10);
        //配置队列大小
        executor.setQueueCapacity(200000);
        //线程存活时间
        executor.setKeepAliveSeconds(600);
        //对多线程设置traceId
        //配置线程池中的线程的名称前缀Common_Thread
        executor.setThreadNamePrefix("user-thread-batch");
        //CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行，由调用线程（提交任务的线程）处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
    }

    public static void main(String[] args) throws Exception {

        String photoScore = "1234567";
        System.out.println(StrUtil.sub(photoScore, 0, 7));
    }

    private static void extracted2() {
        LocalDateTime finishTime = LocalDateTime.now().plusDays(-5);
        LocalDate localDate = finishTime.plusDays(4).toLocalDate();
        LocalDate now = LocalDate.now();
        System.out.println("允许提结时间:" + localDate);
        System.out.println("now:" + now);
        if (localDate.isBefore(now)) {

            System.out.println("允许");
        }

        int x = 3;
        System.out.println(x++ + ++x + ++x);
        System.out.println("------------");

        for (int i = 0; i < 10; i++) {
            System.out.println("i:" + i);
        }
        for (int k = 0; k < 10; ++k) {
            System.out.println("k:" + k);
        }
    }

    private static void aaaaaa() {
        System.out.println(LocalDateTime.parse("2024-11-07 14:50:39", DatePattern.NORM_DATETIME_FORMATTER));

        System.out.println(getRepaymentPeriods(3, 6));

        String json = "[{\"id\":1454,\"userId\":473,\"orderNo\":\"LOAN202408121822921830161035264\",\"data\":{\"data\":{\"data\":{\"userName\":\"李斯\"}}}}]";
    }

    public static String getRepaymentPeriods(int start, int total) {
        List<Integer> periods = new ArrayList<>();
        for (int i = start; i <= total; i++) {
            periods.add(i);
        }
        return StrUtil.join(",", periods);
    }

    private static void extracted1() {
        String json = "{\"id\":1454,\"userId\":473,\"orderNo\":\"LOAN202408121822921830161035264\",\"data\":{\"data\":{\"data\":{\"userName\":\"李斯\"}}}}";

        Void v = null;

        StopWatch stopWatch = StopWatch.create("test");
        stopWatch.start();
        for (int i = 0; i < 200; i++) {
//            String userName = JSON.parseObject(json).getJSONObject("data").getJSONObject("data").getJSONObject("data").getString("userName");
//            String userName1 = JSONUtil.parseObj(json).getJSONObject("data").getJSONObject("data").getJSONObject("data").getStr("userName");
            String userName2 = com.alibaba.fastjson.JSON.parseObject(json).getJSONObject("data").getJSONObject("data").getJSONObject("data").getString("userName");
        }
        stopWatch.stop();
        //8.4056305  fastjson2
        //12.5242508  fastjson1
        //43.7365964  hutool
        System.out.println(stopWatch.getTotalTimeSeconds());

        System.out.println("0xffffcd7d：" + 0xffffcd7d);
    }


    private static void porttest() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            int port = 9090;
            String ip = "192.168.1.12" + ":" + port;
            list.add(ip);
        }
        String join = StrUtil.join(", ", list);
        System.out.println(join);

        String string = "服务【" + "business-server" + "】启动成功，节点:【" + join + "】";
        System.out.println(string);
    }

    private static void cheche() {
        //堆外缓存
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024 * 1024 * 1024);
    }

    private static void idtest() {
        ConcurrentHashSet<Long> set = new ConcurrentHashSet<>(50000);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String mMdd = DateUtil.date().toString("yyMMdd");


        IdGeneratorOptions options = new IdGeneratorOptions();
        // 默认值6，限定 WorkerId 最大值为2^6-1，即默认最多支持64个节点。
        options.WorkerIdBitLength = 3;
        // 默认值6，限制每毫秒生成的ID个数。若生成速度超过5万个/秒，建议加大 SeqBitLength 到 10。
        options.SeqBitLength = 6;
        // 如果要兼容老系统的雪花算法，此处应设置为老系统的BaseTime。
        options.BaseTime = 1099030927000L;
        //目前数据中心只有一个，workID定义最大为6台机器，一个数据中心
        options.WorkerId = (short) IdUtil.getWorkerId(1, 6);
        YitIdHelper.setIdGenerator(options);
        CountDownLatch countDownLatch = new CountDownLatch(50000);
        for (int i = 0; i < 50000; i++) {
            executor.execute(() -> {
                try {
                    long nextId = YitIdHelper.nextId();
//                    long nextId = IdUtil.getSnowflakeNextId();
                    set.add(nextId);
                    System.out.println(nextId);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            countDownLatch.await();
            System.out.println("阻塞");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.shutdown();
        System.out.println("阻塞完成" + countDownLatch.getCount());
        System.out.println(set.size());
        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeSeconds());


//        HashSet<Long> set2 = new HashSet<>();
//        StopWatch stopWatch2 = new StopWatch();
//        stopWatch2.start();
//        SnowflakeIdTool snowflakeIdTool = new SnowflakeIdTool(1, 1);
//        System.out.println(snowflakeIdTool.nextIdToString());
//        for (int i = 0; i < 10000; i++) {
//            set2.add(snowflakeIdTool.nextId());
//        }
//        System.out.println(set2.size());
//        stopWatch2.stop();
//        System.out.println(stopWatch2.getTotalTimeSeconds());

//        long dataCenterId = IdUtil.getDataCenterId(1);
//        long workerId = IdUtil.getWorkerId(dataCenterId, 10);
//        Date epochDate = DateUtil.date(1631603097000L);
//        Snowflake snowflake = new Snowflake(epochDate, workerId, dataCenterId, false);
//        System.out.println(snowflake.nextIdStr());
    }

    private static void strmore() {

        String s = "\"{\\\"code\\\":0,\\\"data\\\":[{\\\"id\\\":1454,\\\"createTime\\\":\\\"2024-08-12 17:03:27\\\",\\\"updateTime\\\":\\\"2024-09-09 16:21:20\\\",\\\"creator\\\":473,\\\"creatorName\\\":null,\\\"updater\\\":473,\\\"updaterName\\\":\\\"scheduler\\\",\\\"deleted\\\":0,\\\"userId\\\":473,\\\"orderNo\\\":\\\"LOAN202408121822921830161035264\\\",\\\"orderRepayStatus\\\":\\\"repay_early\\\",\\\"loanAmt\\\":1000,\\\"loanTime\\\":\\\"2024-08-12 17:14:21\\\",\\\"createResult\\\":null,\\\"issued\\\":\\\"0\\\",\\\"productNo\\\":\\\"AAA\\\",\\\"useFunds\\\":\\\"5\\\",\\\"useFundsDic\\\":\\\"婚庆\\\"}],\\\"msg\\\":\\\"ok\\\",\\\"traceId\\\":\\\"810d7b1909514a94b287c94650e27304\\\",\\\"responseTime\\\":\\\"2024-09-12T18:02:02.839\\\"}\"";

        String str = StringEscapeUtils.unescapeJava(s);
        StringBuilder deleteStr = new StringBuilder(str).delete(0, 1).delete(str.length() - 1, str.length());
        str = JSONUtil.toJsonStr(deleteStr);
        System.out.println(str);
        JSONObject jsonObject = JSONUtil.parseObj(str);
        String o = jsonObject.getStr("traceId");
        System.out.println(o);
    }

    private static void extracted() throws InterruptedException {
        ScheduledExecutorService e = Executors.newScheduledThreadPool(0);
        e.schedule(() -> {
            System.out.println("业务逻辑");
        }, 0, TimeUnit.SECONDS);
        e.shutdown();

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Thread.sleep(1000);
        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeSeconds());
        System.out.println(JdkUtil.JVM_VERSION);
    }


}
